---@coding utf8

require "lua_src.xlib.sandbox.sandbox"
MinHeapM = sbx_import("lua_src.xlib.xcontainer.min_heap.lua")


---@class TimeoutMap_Node
---@field key any
---@field value any
---@field timeout integer  # 到期时间(只要求数值类型)

---@brief 带超时扫描的map
---@class TimeoutMap
TimeoutMap = TimeoutMap or {}

function TimeoutMap.new(...)
    local obj = {}
    setmetatable(obj, {__index = TimeoutMap})
    obj:_constructor(...)
    return obj
end

function TimeoutMap:_constructor(...)
    ---@type MinHeap
    self.min_heap = MinHeapM.MinHeap.new(...)
    ---@type table<any, TimeoutMap_Node>
    self.k2node = {}
    ---@type table<integer, table<any,boolean>>
    self.timeout2key_set = {}
end

---@brief 插入对象
---@param key any
---@param value any
---@param timeout integer  # 用于超时管理的数值类型
function TimeoutMap:Insert(key, value, timeout)
    local node = self.k2node[key]
    --- 如果需要修改超时实现需要先把时间索引删除掉
    if node then
        node.value = value
        if node.timeout == timeout then
            return
        end
        -- 移出旧超时信息
        local old_key_set = self.timeout2key_set[node.timeout]
        if old_key_set then
            old_key_set[key] = nil
            if not next(old_key_set) then
                self.timeout2key_set[node.timeout] = nil
            end
        end
    else
        node = {key = key, value = value, timeout = timeout}
    end
    --- 数据插入完成，开始插入超时管理数据
    local key_set = self.timeout2key_set[timeout]
    if not key_set then
        key_set = {[key] = true}
        self.timeout2key_set[timeout] = key_set
        self.min_heap:Push(timeout)
    else
        key_set[key] = true
    end
end

function TimeoutMap:Get(key)
    local node = self.k2node[key]
    if not node then
        return
    end
    return node.value
end

function TimeoutMap:ScanTimeoutKeys(timeout)
end

function TimeoutMap:ScanAndDelTimeoutKeys(timeout)
end